<?php

namespace app\admin\model;

use think\Model;

use think\Db;
use think\Request;
use think\Exception;//事务处理

class Coattr extends Model
{
    public function getcoattr($res)
    {
        $langs = $where['a.lang'] = $res['lang'];//语言标志
        $join = [
            ['nt_coattr b', 'a.mkey=b.mkey']
        ];
        $table = 'multi_lang';
        $pagelimit['limit'] = $res['pageSize'];
        $pagelimit['start'] = ($res['page'] - 1) * $res['pageSize'];
        $datares = getmultidata($table, $join, $where, $pagelimit, null);//获取的是对应的语言属性名称
        foreach ($datares['data'] as $datareskey => $dataresval) {
            //获取对应的语言公司类型名称
            $datares['data'][$datareskey]['cotypename'] = $this->getcotype($dataresval['cotype_ids'], $langs);
            if ($dataresval['is_text'] == 1) {
                $datares['data'][$datareskey]['textselect'] = lang("select_box");
            } else {
                $datares['data'][$datareskey]['textselect'] = lang("text");
            }
            $datares['data'][$datareskey]['country'] = getcountry($dataresval['country_id']);//国家
            if ($dataresval['person'] == 1) {
                //适用个人
                $datares['data'][$datareskey]['personman'] = '+';
            } else {
                $datares['data'][$datareskey]['personman'] = '-';
            }
            //编辑时间
            $datares['data'][$datareskey]['update_date'] = getTimeDate($dataresval['update_at'], 12);
            //编辑者
            $datares['data'][$datareskey]['mangname'] = getinfo($dataresval['update_id'], 'admin')['nickname'];//编辑者
        }
        $data['data'] = $datares['data'];
        $data['count'] = $datares['count'];
        return $data;
    }

    //获取对应的公司类型的名称
    protected function getcotype($cotype_ids, $langs)
    {
        $cotypearr = explode(',', $cotype_ids);
        foreach ($cotypearr as $cotypearrkey => $cotypearrval) {
            $where['mkey'] = 'cotype_' . $cotypearrval;
            //对应下的语言名称
            $cotypname[] = getlangname('multi_lang', $where, $langs);
        }
        return implode(' / ', $cotypname);
    }

    //公司属性的添加编辑
    public function addeditcoattr($data)
    {
        $langwage = getables('language', ['status' => 1], 'code');
        if ($data['act'] == 'coattradd') {
            $ckdata = notEmpty(['coattrname' => lang("attribute_name")]);
            if ($ckdata['status'] == 2) {
                return $ckdata;
            }
        } else {
            //编辑的判断
            foreach ($langwage as $langwagekey => $langwageval) {
                $langcode = 'lang_' . $langwageval['code'];
                if (!isset($data[$langcode])) {
                    return array('msg' => lang('attribute_name') . lang("can't_be_empty"), 'status' => 2);
                }
                if (isset($data[$langcode]) && !$data[$langcode]) {
                    return array('msg' => lang('attribute_name') . lang("can't_be_empty"), 'status' => 2);
                }
            }
        }
        //公司类型
        if (!isset($data['cotype_ids'])) {
            return array('msg' => lang("company_typo_can't_be_empty"), 'status' => 2);
        }
        $lang = $data['lang'];
        unset($data['lang']);
        //公司类型
        $datadepart['cotype_ids'] = $data['cotype_ids'] = implode(',', array_unique(array_filter($data['cotype_ids'])));
        if ($data['is_text'] == 1) {
            //选择框不能为空
            if (!isset($data['option_text'])) {
                return array('msg' => lang("select_box_can't_be_empty"), 'status' => 2);
            }
            $option_text = array_column($data['option_text'], 'option_text');
            //判断是否含有空值
            if (in_array('', $option_text)) {
                return array('msg' => lang("select_box_can't_contain_null_values"), 'status' => 2);
            }
            //判断是否含有重复的值
            $countone = count(array_filter($option_text));//去空后的个数
            $counttwo = count(array_unique(array_filter($option_text)));//去重去空后的个数
            if ($countone != $counttwo) {
                return array('msg' => lang("select_box_contains_duplicate_values"), 'status' => 2);
            }
        }
        if ($data['act'] == 'coattradd') {
            unset($data['id']);
            $depalike = 'coattr';
            $langwhere['mkey'] = array('like', $depalike . '%');
            $coattrname = $langwhere['content'] = trim($data['coattrname']);
            $langzh = getables('multi_lang', $langwhere);
            if ($langzh) {
                return array('msg' => lang("company_attribute_exists"), 'status' => 3);
            }
            $data['create_at'] = $data['update_at'] = time();
            $data['create_id'] = session('userid');
            //开启事务
            Db::startTrans();
            $coattrid = $this->strict(false)->insertGetId($data);//公司属性表
            $coattrkey = 'coattr_' . $coattrid;
            //更新数据
            $this->where('id', $coattrid)->setField('mkey', $coattrkey);
            $multidata = array();
            foreach ($langwage as $langdatakey => $langdataval) {
                $multidata[$langdatakey]['content'] = $coattrname;
                $multidata[$langdatakey]['mkey'] = $coattrkey;
                $multidata[$langdatakey]['lang'] = $langdataval['code'];
            }
            $langid = Db::name('multi_lang')->insertAll($multidata);//语言表
            //选择框
            if ($data['is_text'] == 1) {
                $rescoattr = [];
                if ($counttwo) {
                    for ($i = 0; $i < $counttwo; $i++) {
                        $row = [
                            'coattr_id' => $coattrid,//属性的id
                            'option_text' => $data['option_text'][$i]['option_text'],//所属公司类型
                        ];
                        $rescoattr[] = $row;
                    }
                    //选择框中的值
                    $resids = Db::name('coattr_select')->insertAll($rescoattr);
                }
            } else {
                $resids = 1;
            }
            if ($coattrid && $langid && $resids) {
                Db::commit();
                return array('msg' => $coattrname . lang("added_successfully"), 'status' => 1);
            } else {
                return array('msg' => $coattrname . lang("add_failed"), 'status' => 0);
            }
        } elseif ($data['act'] == 'coattredit') {
            $langedit = $data['lang_' . $lang];//编辑的资料属性
            //开启事务
            Db::startTrans();
            //删除select的选择框
            Db::name('coattr_select')->where('coattr_id', $data['id'])->delete();
            $datadepart['update_at'] = time();
            $datadepart['is_text'] = $data['is_text'];
            $datadepart['country_id'] = $data['country_id'];
            $datadepart['person'] = $data['person'];
            $datadepart['update_id'] = session('userid');
            //更新属性表
            $resid = $this->where('id', $data['id'])->update($datadepart);
            //更新语言表
            $departmkey = 'coattr_' . $data['id'];
            foreach ($langwage as $langewagekey => $langwageval) {
                $langekey = 'lang_' . $langwageval['code'];
                $depaname = trim($data[$langekey]);//编辑的公司属性
                //发现没有这个语言
                $infolang = Db::name('multi_lang')->where(['mkey' => $departmkey, 'lang' => $langwageval['code']])->find();
                //存在更新
                if ($infolang) {
                    $rename = Db::name('multi_lang')->where(['mkey' => $departmkey, 'lang' => $langwageval['code']])->setField('content', $depaname);
                } else {
                    //写入数据
                    $insertdata['mkey'] = $departmkey;
                    $insertdata['lang'] = $langwageval['code'];
                    $insertdata['content'] = $depaname;
                    $rename = Db::name('multi_lang')->insert($insertdata);
                }
            }
            //重新写入select表
            if ($data['is_text'] == 1) {
                foreach ($data['option_text'] as $datakeys => $datavals) {
                    $datavals['coattr_id'] = $update['coattr_id'] = $data['id'];
                    if ($datavals['id']) {
                        $update['id'] = $datavals['id'];
                        $update['option_text'] = $datavals['option_text'];
                        Db::name('coattr_select')->insert($update);
                    } else {
                        //继续写入并保持自增状态
                        Db::name('coattr_select')->strict(false)->insert($datavals);
                    }
                    $resids = 1;
                }
            } else {
                $resids = 1;
            }
            if ($resid !== false && $rename !== false && $resids) {
                Db::commit();
                return array('msg' => $langedit . lang("edited_successfully"), 'status' => 1);
            } else {
                return array('msg' => $langedit . lang("edit_failed"), 'status' => 0);
            }
        }
    }

    //公司属性的删除
    public function delcoattr($data, $code)
    {
        $lang = $data['langs'];
        //查询具体语言下的部门
        $coattrwhere['mkey'] = 'coattr_' . $data['id'];
        $langname = getlangname('multi_lang', $coattrwhere, $lang);
        //是固定的字段不允许删除
        $fix = $this->where('id', $data['id'])->find()['fix'];
        if ($fix == '1') {
            return array('msg' => $langname . '已经被固定，无法删除', 'status' => 0);
        }
        $coattr = Db::name('coattr_value')->where('coattr_id', $data['id'])->select();
        if ($coattr) {
            return array('msg' => $langname . lang("contains_corresponding_company_and_can't_be_deleted"), 'status' => 0);
        }
        if ($code == 1) {
            $updelete['del_at'] = time();
            $updelete['del_id'] = session('userid');
            $retrole = $this->where('id', $data['id'])->update($updelete);//属性表
        } else {
            $retrole = $this->where('id', $data['id'])->delete();
            //删除语言表
            Db::name('multi_lang')->where('mkey', 'coattr_' . $data['id'])->delete();
            //删除属性表
            Db::name('coattr_select')->where('coattr_id', $data['id'])->delete();
        }
        if ($retrole !== false) {
            return array('msg' => $langname . lang("deleted_successfully"), 'status' => 1);
        } else {
            return array('msg' => $langname . lang("failed_to_delete"), 'status' => 0);
        }
    }
}


